<?php

class PartyController extends Controller
{

	/**
     * 过滤器
	 * @return 返回值是一个存放过滤器的数组
	 */
	public function filters()
	{
		return array(
            'accessAuth',//自定义授权方式
			//'accessControl', //默认授权方式
			'postOnly + delete',//删除操作只支持post请求
		);
	}
    /**
     * 自定义权限验证规则
     * @param type $filterChain
     * @throws CHttpException
     */
    public function filterAccessAuth($filterChain) {  
        if(Yii::app()->user->getIsGuest()) {  
            echo '<script>top.location.href="'.Yii::app()->user->returnUrl.'";</script>';
            exit;
        } else if(!Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())){
            throw new CHttpException(403,'无权访问此页面');
        }
        $filterChain->run();  
    }  
    /**
     * 页面白名单
     * @return type
     */
    public function authlessActions() {  
        return array(
            'index','admin','view','create','update','delete','adminClander','activityMsg',
            'childrenMsg','recommendMsg','preview','adlist','blackList','cancelList','checkParty',
            'print','batchCreate','changeParty','updateLine','sendMeg','upload'
		); 
    }

	/**
	 * 查看页面
	 * @param integer $id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionCreate()
	{
		$model=new Party;

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);
                
		if(isset($_POST['Party']))
		{
                        $transaction = Yii::app()->db->beginTransaction(); //创建事务
			$model->attributes=$_POST['Party'];
                        $model->add_time=date('Y-m-d H:i:s',time());
                        $model->update_time=date('Y-m-d H:i:s',time());
                        $model->update_id=Yii::app()->user->username;
                        //来源
                        $model->is_origin=1;
                        //是否来访
                        $model->is_from=1;
                        //发送状态
                        $model->is_send=0;
                        //黑名单
                        $model->is_float=0; 
                        //默认地址
                        $model->is_use=1;
                        //年龄
                        $model->age=$this->getAgeByCode( $model->code);                        
                        //用户识别码
                        $temp_code;
                        $snumber=new Snumber();
                        $snumber->add_time=date('y-m-d H:i:s',time());
                        if($snumber->save()){
                           $temp_code=$snumber->attributes['id'];
                        }else{
                             $transaction->rollback(); //回滚事务
                             Yii::app()->end();
                             die();           
                        }
//                        $model->user_code=date('Ymd',time()).str_pad($temp_code,6,"0",STR_PAD_LEFT).$this->generate_code(2);
                        $model->user_code="2".substr(date('Y',time()),2).str_pad($temp_code,6,"0",STR_PAD_LEFT);
                        $model->vcode="0000";
                        

			if($model->save()){
                            //新增地址逻辑
                            //先改用户表的内容
                            $p_count=Party::model()->updateAll(array('is_use'=>'0'),"phone='".$model->phone."' and code='".$model->code."' and id !=".$model->primaryKey);
                            if($p_count>0){
                                //再修改新增表的地址
                                $n_count=Naddress::model()->updateAll(array('is_used'=>'0'),"phone='".$model->phone."' and code='".$model->code."'");
                            } 
                            $transaction->commit(); //提交事务
                            if($_POST['ad_id']>0){
                                Yii::app()->user->setFlash('success','操作成功！');
                                $this->redirect(array('activityDetail/update','id'=>$_POST['ad_id']));                                    
                            }  else {
                                Yii::app()->user->setFlash('success','操作成功！');
                                $this->redirect(array('Party/admin'));                                   
                            }
                        }
		}
                $type=0;
                if(isset($_GET['type'])){
                    $type=1;
                }
                $ad_id=0;
                if(isset($_GET['ad_id'])){
                    $ad_id=$_GET['ad_id'];
                }
		$this->render('create',array(
			'model'=>$model,
                        'type'=>$type,
                        'ad_id'=>$ad_id,
		));
	}
        
        
        /**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionUpload()
	{
		$pmodel=new Party;

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);
                
                if(isset($_POST['Party']))
		{
                    
                $pmodel->attributes=$_POST['Party'];
                
		if(!empty($_POST['userfile'])){       
                $path=$_POST['userfile'];
                $len=strlen($path);
//              $index=strpos($path,'/',2);
                $index=strpos($path,'/',4);
                $path=substr($path,$index+1,$len);
//                $path="editor/attached/excel/20150928/20150928120252_31535.xlsx";
                include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel/PHPExcel/IOFactory.php');  
                $reader = PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文件
                $PHPExcel = PHPExcel_IOFactory::load($path);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表(编号从 0 开始)  
                $highestRow = $sheet->getHighestRow(); // 取得总行数  
                $highestColumn  = $sheet->getHighestColumn(); // 取得总列数  
                $transaction = Yii::app()->db->beginTransaction(); //创建事务
                for ($row = 2; $row <= $highestRow; $row++) { 
                    $data = array();
                    for ($column = 0; $column <= 13; $column++)  {  
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue(); 
//                        $val = iconv("utf-8","gbk",$val);
                        $data[$column]=$val;  
                    }
                    $model=new Party;
                    $model->unsetAttributes();  
                    // 用户识别码
                    $connection = Yii::app()->db;
                    $sql = "SELECT IFNULL(MAX(id),0) as max_id FROM party";  
                    $command = $connection->createCommand($sql);  
                    $result = $command->queryAll();  
                    $num=$result[0]['max_id']+1;  
                    $num=sprintf("%06d", $num);
                    $user_code=''.date('Ymd',time()).''.$num.rand(10,100);
                    $model->ad_id=$pmodel->ad_id;
                    $model->crowd_id=$pmodel->crowd_id;
                    $model->line_id=$pmodel->line_id;
                    $model->username=$data[0];
                    $model->phone=$data[1];
                    $model->code=$data[2];
                    try {
                         $model->age=$this->getAgeByCode($data[2]);
                    } catch (Exception $exc) {
                        Yii::app()->user->setFlash('code_error','身份证信息错误！');
                        $this->redirect(array('Party/create'));
                        return;
                    }
                    $model->sex=$data[3];
                    $model->province=$data[4];
                    $model->city=$data[5];
                    $model->area=$data[6];
                    $model->address=$data[7];
                    $model->company=$data[8];
                    $model->children_num=$data[9];
                    $model->recommend=$data[10];
                    $model->user_code=$user_code;
                    $model->add_time=date('Y-m-d H:i:s',time());
                    $model->update_time=date('Y-m-d H:i:s',time());
                    $model->update_id=Yii::app()->user->username;
                    //来源
                    $model->is_origin=1;
                    //是否来访
                    $model->is_from=1;
                    //发送状态
                    $model->is_send=0;
                    //黑名单
                    $model->is_float=0;  
                    //
                    $snumber=new Snumber();
                    $snumber->add_time=date('y-m-d H:i:s',time());
                    if($snumber->save()){
                        $temp_code=$snumber->attributes['id'];
                    }else{
                        $transaction->rollback(); //回滚事务
                        Yii::app()->end();
                        die();
                    }
//                    $model->user_code=date('Ymd',time()).str_pad($temp_code,6,"0",STR_PAD_LEFT).$this->generate_code(2);
                    $model->user_code="2".substr(date('Y',time()),2).str_pad($temp_code,6,"0",STR_PAD_LEFT);
                    $model->vcode="0000";                    
                    if($model->save()){}
                     else {
                        $transaction->rollback(); //回滚事务
                        Yii::app()->end();
                        die();
                     }
                }
             
                
                $sheet2 = $PHPExcel->getSheet(1); // 读取第一個工作表(编号从 0 开始)  
                $highestRow2 = $sheet2->getHighestRow(); // 取得总行数  
                $highestColumn2  = $sheet2->getHighestColumn(); // 取得总列数
                
                
                
                $cmodel=new Children();
                for ($row = 2; $row <= $highestRow2; $row++){
                    
                    $data = array();
                    for ($column = 0; $column <= 10; $column++)  {  
                        $val = $sheet2->getCellByColumnAndRow($column, $row)->getValue(); 
//                        $val = iconv("utf-8","gbk",$val);
                        $data[$column]=$val;  
                    }
                    
                    
                      $t_phone=$data[0];
                      $t_code=$data[1];
                      $t_party=  Party::model()->find("ad_id=".$pmodel->ad_id." and phone='".$t_phone."' and code='".$t_code."'");
                      if(!empty($t_party)){
                            $cmodel->party_id=$t_party->id;
                            $cmodel->username=$data[2];
                            $cmodel->sex=$data[3];
                            $cmodel->age=$data[4];
                            $cmodel->grade=$data[5];
                            $cmodel->school=$data[6];
                            if($cmodel->save()){}
                            else{
                                $transaction->rollback(); //回滚事务
                                Yii::app()->end();
                                die();  
                            }
                      }
                      
                     
                 }

                $transaction->commit(); //提交事务
                Yii::app()->user->setFlash('success','操作成功！');
                $this->redirect(array('Party/admin'));                                 
                }  else {
                     Yii::app()->user->setFlash('upload_error','请选择上传文件！');
                    $this->redirect(array('Party/upload'));                   
                }
            
            }
            
            
            $this->render('upload',array(
			'model'=>$pmodel,
                        'type'=>0,
                        'ad_id'=>0,
		));
	}
        

	/**
	 * 修改页面
	 * 如果修改成功，跳转到查看页面
	 * @param integer $id 
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['Party']))
		{
			$model->attributes=$_POST['Party'];
			if($model->save()){
                            if(!empty($_POST['party_type'])){
                                if($_POST['party_type']=="party" || $_POST['party_type']=="clander"){
                                    Yii::app()->user->setFlash('success','操作成功！');
                                    $this->redirect(array('activityDetail/update','id'=>$model->ad_id));
                                }  else {
                                    Yii::app()->user->setFlash('success','操作成功！');
                                    $this->redirect(array('Party/admin'));                                    
                                }
                            }  else {
                                Yii::app()->user->setFlash('success','操作成功！');
                                $this->redirect(array('Party/admin'));                                
                            }                            
                        }
		}
                $type="1";
                if(isset($_GET['type'])){
                    $type=$_GET['type'];
                }
                $model_p=Party::model()->find("is_use=1 and phone='".$model->phone."' and code='".$model->code."'");                
                if(count($model_p)<=0){
                    $model_n=Naddress::model()->find("is_used=1 and phone='".$model->phone."' and code='".$model->code."'");
                    if(count($model_n)<=0){
                        $this->render('update',array(
                                'model'=>$model,
                                'type'=>$type,
                                'model_pn'=>null,
                        ));                        
                    }  else {
                        $this->render('update',array(
                                'model'=>$model,
                                'type'=>$type,
                                'model_pn'=>$model_n,
                        ));                        
                    }
                }  else {
                    $this->render('update',array(
                            'model'=>$model,
                            'type'=>$type,
                            'model_pn'=>$model_p,
                    ));                    
                }
	}

	/**
	 * 删除功能
	 * 一般只接受post方式的异步提交
	 * @param integer $id 
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    //获取id数组批量删除
                    $criteria= new CDbCriteria;
                    $criteria->addInCondition('id', $id);
                    
                    $criteria_c= new CDbCriteria;
                    $criteria_c->addInCondition('party_id', $id);
                    $c_count=Children::model()->count($criteria_c);
                    if($c_count>0){
                          echo CJSON::encode(array('result'=>-1));
                    }else{
                        $res=Party::model()->deleteAll($criteria);
                        //输出json结果
                        echo CJSON::encode(array('result'=>$res));
                    }
                    
                    
                    
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
	}

	/**
	 * 列表页
	 */
	public function actionAdmin()
	{
		$model=new Party('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Party']))
			$model->attributes=$_GET['Party'];
                if(!empty($_GET['Party_age_1']) && !empty($_GET['Party_age_2'])){
                    $age_1=$_GET['Party_age_1'];
                    $age_2=$_GET['Party_age_2'];
                    $recommend=0;
                    if(!empty($_GET['is_recommend'])){
                        $recommend=$_GET['is_recommend'];
                    }
                    $this->render('admin',array(
                            'model'=>$model,
                            'data'=>$model->search_age($age_1,$age_2,$recommend),
                    ));  
                    return;
                }
                if(!empty($_GET['is_recommend'])){
                    $recommend=$_GET['is_recommend'];
                    $this->render('admin',array(
                            'model'=>$model,
                            'data'=>$model->search_recommendeds($recommend,0),
                    ));  
                    return;                    
                }                
		$this->render('admin',array(
			'model'=>$model,
			'data'=>$model->search(),
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Party the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Party::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Party $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='party-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	/**
	 * 列表页
	 */
	public function actionAdminClander()
	{
		$model=new Party('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['Party']))
			$model->attributes=$_GET['Party'];
                if(!empty($_GET['detail_id'])){
                    $model->ad_id=$_GET['detail_id'];
                }
                $is_children=0;
                $recommend=0;
                if(!empty($_GET['is_children'])){
                    $is_children=$_GET['is_children'];
                    if(!empty($_GET['is_recommend'])){
                        $recommend=$_GET['is_recommend'];
                    }
                    $this->render('adminClander',array(
                            'model'=>$model,
                            'data'=>$model->search_recommendeds($recommend,$is_children),
                    ));  
                    return;                     
                }
                if(!empty($_GET['is_recommend'])){
                    $recommend=$_GET['is_recommend'];
                    $this->render('adminClander',array(
                            'model'=>$model,
                            'data'=>$model->search_recommendeds($recommend,$is_children),
                    ));  
                    return;                    
                }                  
		$this->render('adminClander',array(
			'model'=>$model,
			'data'=>$model->search_date(),
		));
	}
	/**
	 * 参加活动情况
	 */
	public function actionActivityMsg()
	{       
		$model=new Party('search');
		$model->unsetAttributes();  //清空并初始化
                $phone="";
                $code="";
                if(isset($_GET['phone'])){
                    $phone=$_GET['phone'];
                }
                if(isset($_GET['code'])){
                    $code=$_GET['code'];
                }
		$this->render('activityMsg',array(
			'model'=>$model,
			'data'=>$model->search_msg($phone,$code),
		));
	}   
	/**
	 * 我的推荐
	 */
	public function actionRecommendMsg()
	{       
		$model=new Party('search');
		$model->unsetAttributes();  //清空并初始化
                $recommend="";
                if(isset($_GET['recommend'])){
                    $recommend=$_GET['recommend'];
                }
		$this->render('recommendMsg',array(
			'model'=>$model,
			'data'=>$model->search_recommended($recommend),
		));
	}
        public function actionPreview()
        {
            $data=new ActivityDetail();
            if(!empty($_POST['ad_id']))
                $data = ActivityDetail::model()->find('id=:id',array(':id'=>(int)$_POST['ad_id']));
            else
                $data->title='';
                
            echo CJSON::encode(array(
                'title'=>$data->activity->title,
               
            ));
        } 
        public function getCount($phone,$code)
        {
            $connection = Yii::app()->db;
            $sql = "SELECT count(*) as count FROM party  WHERE phone = '".$phone."' AND code='".$code."'";  
            $command = $connection->createCommand($sql);  
            $result = $command->queryAll();  
            $num=$result[0]['count'];   
            return $num;            
        }
        
        
        /**
	 * 下拉列表获取活动明细.
	 */
        public function actionAdlist(){
//            if(Yii::app()->request->isAjaxRequest && isset($_POST['aid'])){
//
//                 $aid = (int)$_POST['aid'];
//                 $data=ActivityDetail::model()->findAll('activity_id='.$aid);
//                 $data = CHtml::listData($data,'id','start');
//                 echo  CHtml::tag('option',array('value'=>''),CHtml::encode("--请选择活动时间--"),true);
//                 foreach($data as $value=>$name){
//                    echo  CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
//                }
//                  
//             }
            if(Yii::app()->request->isAjaxRequest && isset($_POST['aid'])){
            //Cities
                $data = ActivityDetail::model()->findAll('activity_id=:activity_id', array(':activity_id'=>(int) $_POST['aid']));
                $data = CHtml::listData($data,'id','begins');
                $dropDownCities = "<option value=''>--请选择活动时间--</option>";
                foreach($data as $value=>$name)
                    $dropDownCities .= CHtml::tag('option', array('value'=>$value),date("Y-m-d",strtotime($name)),true);

                //District
                $dropDownDistricts = "<option value=''>--选择上车地址--</option>";

                // return data (JSON formatted)
                echo CJSON::encode(array(
                    'dropDownCities'=>$dropDownCities,
                    'dropDownDistricts'=>$dropDownDistricts
                ));
            }
            
        }
        
        
        public function actionUpdateLine()
        {
            $data = LineDetail::model()->findAll('ad_id=:ad_id', array(':ad_id'=>(int) $_POST['ad_id']));
            $data = CHtml::listData($data,'id','position.address');
            echo "<option value=''>--选择上车地址--</option>";
            foreach($data as $value=>$name)
                echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
        }
        
        
        public function actionCancelList($id){
              if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    $res=0;
                    //获取id数组批量删除
                    $criteria= new CDbCriteria;
                    $criteria->addInCondition('id', $id);
                    $model=Party::model()->findAll($criteria);
                    foreach ($model as $val){
                        Blacklist::model()->deleteAll("phone='".$val->phone."' and code='".$val->code."'");
                    }

                //$res=Party::model()->deleteAll($criteria);
                    //输出json结果
                    echo CJSON::encode(array('result'=>$res));
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
            
        }
        
        
         public function actionBlackList($id){
             if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    $res=0;
                    //获取id数组批量删除
                    $criteria= new CDbCriteria;
                    $criteria->addInCondition('id', $id);
                    $model=Party::model()->findAll($criteria);
                    foreach ($model as $val){
                        $count=Blacklist::model()->count("phone='".$val->phone."' and code='".$val->code."'");
                           //避免重复拉黑
                          if($count<=0){
                                    $black=new Blacklist();
                                    $black->username=$val->username;
                                    $black->sex=$val->sex;
                                    $black->phone=$val->phone;
                                    $black->company=$val->company;
                                    $black->code=$val->code;
                                    $black->province=$val->province;
                                    $black->city=$val->city;
                                    $black->area=$val->area;
                                    $black->address=$val->address;
                                    $black->is_float=0;
                                    if($black->save()){

                                    }else{
                                        $res=1;
                                    }
                        }
                    }

                //$res=Party::model()->deleteAll($criteria);
                    //输出json结果
                    echo CJSON::encode(array('result'=>$res));
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
            
        }
        
         public function actionCheckParty($id){
             if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    
                    $criteria= new CDbCriteria;
                    $criteria->addInCondition('id', $id);
                    $list=Party::model()->findAll($criteria);
                    $res=0;
                    foreach ($list as $model){
                        $model->is_float=1;
                        $model->is_send=1;
                        //输出json结果
                        $ad=ActivityDetail::model()->findByPk($model->ad_id);
                        $smsmodel=Sms::model()->find('activity_id='.$ad->activity_id.' and is_type=2');
                        if($model->save()&&!empty($smsmodel)){
                            
                             //"您已成功预约‘欣和爱生活食育体验馆’的参观，具体详见电子门票，并截图保存，请提前15分钟到达指定地点乘车，谢谢！电子门票："
                            $url_temp=Yii::app()->request->hostInfo."/ex/sign/index.php/default/result?val=".base64_encode($this->generate_code(8).$model->id);
                            $url=(string)Ccommon::url_short($url_temp);
                           
                            $s_txt =$smsmodel->content.$url."。";
                           
                            //发送短信
                            $ad=ActivityDetail::model()->findByPk($model->ad_id);
                            $url_temp=Yii::app()->request->hostInfo."/ex/sign/index.php/default/result?val=".base64_encode($this->generate_code(8).$model->id);
                            $url=(string)  Ccommon::url_short($url_temp);
                            $s_txt =Sms::model()->find('activity_id='.$ad->activity_id.' and is_type=2')->content.$url."。";
                            Ccommon::smsMessage($model->phone,$s_txt);
                            //短信日志
                            $sms_log=new SmsLog;
                            $sms_log->activity_id=$ad->activity_id;
                            $sms_log->sms_type=2;//1为友情提示2为电子门票短信
                            $sms_log->name=$model->username;
                            $sms_log->phone=$model->phone;
                            $sms_log->send_time=date('Y-m-d H:i:s',time());
                            $sms_log->sms_content=$s_txt;
                            $sms_log->save();
                        }else{
                            $res=1;
                        } 
                    }

                    
                  
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
            
        }
        
        
         public function actionSendMeg($id){
             if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    $criteria= new CDbCriteria;
                    $criteria->addInCondition('id', $id);
                    $list=Party::model()->findAll($criteria);
                    $res=0;
                    foreach ($list as $model){
                            //发送短信
                            $ad=ActivityDetail::model()->findByPk($model->ad_id);
                           
                            $s_txt =Sms::model()->find('activity_id='.$ad->activity_id.' and is_type=3');
                             if(empty($s_txt)){
                               echo CJSON::encode(array('result'=>1));
                               return;
                            }else{
                                  Ccommon::smsYX($model->phone,$s_txt->content);
                                  //短信日志
                                  $sms_log=new SmsLog;
                                  $sms_log->activity_id=$ad->activity_id;
                                  $sms_log->sms_type=1;//1为友情提示2为电子门票短信
                                  $sms_log->name=$model->username;
                                  $sms_log->phone=$model->phone;
                                  $sms_log->send_time=date('Y-m-d H:i:s',time());
                                  $sms_log->sms_content=$s_txt->content;
                                  $sms_log->save();
                            }
    
                    }
                     echo CJSON::encode(array('result'=>$res));
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
            
        }
        
        
        
        
         public function actionChangeParty(){
              if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                    $id=$_POST['id'];
                    $res=0;
                    $model=new Party;
                    $model=Party::model()->findByPk($id);
                    $type=$_POST['type'];
                    if($type==0){
                        $model->is_from=1;
                    }elseif ($type==1) {
                        $model->is_from=3;
                    }  else {
                        $model->is_from=0;
                    }
//                    $model->is_float=1;
                    //输出json结果
                    if($model->save()){
                         $res=0;
                    }else{
                        $res=1;
                    }
                     echo CJSON::encode(array('result'=>$res));
                  
                }else{
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                } 
            
        }        
        //打印
        public function actionPrint(){
		$model=new Party('search_print');
		$model->unsetAttributes();  //清空并初始化
                if(isset($_GET['Party'])){
                    $model->attributes=$_GET['Party'];
                }
                if(isset($_GET['detail_id'])){
                    $model->ad_id=$_GET['detail_id'];
                }   

		$this->render('print',array(
			'model'=>$model->search_print(),
		));                
        }
        //批量导入
        public function actionBatchCreate(){
//            if(isset($_POST['submit'])){              
            if(!empty($_POST['userfile'])){
                $path=$_POST['userfile'];
                $len=strlen($path);
//              $index=strpos($path,'/',2);
                $index=strpos($path,'/',4);
                $path=substr($path,$index+1,$len);
//                $path="editor/attached/excel/20150928/20150928120252_31535.xlsx";
                include_once(dirname(dirname(__FILE__)).'\extensions\PHPExcel\PHPExcel\IOFactory.php');  
                $reader = PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文件
                $PHPExcel = PHPExcel_IOFactory::load($path);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表(编号从 0 开始)  
                $highestRow = $sheet->getHighestRow(); // 取得总行数  
                $highestColumn  = $sheet->getHighestColumn(); // 取得总列数  
                $transaction = Yii::app()->db->beginTransaction(); //创建事务
                for ($row = 2; $row <= $highestRow; $row++) { 
                    $data = array();
                    for ($column = 0; $column <= 13; $column++)  {  
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue(); 
//                        $val = iconv("utf-8","gbk",$val);
                        $data[$column]=$val;  
                    }
                    $model=new Party;
                    $model->unsetAttributes();  
                    // 用户识别码
                    $connection = Yii::app()->db;
                    $sql = "SELECT IFNULL(MAX(id),0) as max_id FROM party";  
                    $command = $connection->createCommand($sql);  
                    $result = $command->queryAll();  
                    $num=$result[0]['max_id']+1;  
                    $num=sprintf("%06d", $num);
                    $user_code=''.date('Ymd',time()).''.$num.rand(10,100);
                    $model->ad_id=$data[0];
                    $model->crowd_id=$data[1];
                    $model->line_id=$data[2];
                    $model->username=$data[3];
                    $model->phone=$data[4];
                    $model->code=$data[5];
                    try {
                         $model->age=$this->getAgeByCode($data[5]);
                    } catch (Exception $exc) {
                        Yii::app()->user->setFlash('code_error','身份证信息错误！');
                        $this->redirect(array('Party/create'));
                        return;
                    }
                    $model->sex=$data[6];
                    $model->province=$data[7];
                    $model->city=$data[8];
                    $model->area=$data[9];
                    $model->address=$data[10];
                    $model->company=$data[11];
                    $model->children_num=$data[12];
                     $model->recommend=$data[13];
                    $model->user_code=$user_code;
                    $model->add_time=date('Y-m-d H:i:s',time());
                    $model->update_time=date('Y-m-d H:i:s',time());
                    $model->update_id=Yii::app()->user->username;
                    //来源
                    $model->is_origin=1;
                    //是否来访
                    $model->is_from=1;
                    //发送状态
                    $model->is_send=0;
                    //黑名单
                    $model->is_float=0;  
                    //
                    $snumber=new Snumber();
                    $snumber->add_time=date('y-m-d H:i:s',time());
                    if($snumber->save()){
                        $temp_code=$snumber->attributes['id'];
                    }else{
                        $transaction->rollback(); //回滚事务
                        Yii::app()->end();
                        die();           
                    }
//                    $model->user_code=date('Ymd',time()).str_pad($temp_code,6,"0",STR_PAD_LEFT).$this->generate_code(2);
                    $model->user_code="2".substr(date('Y',time()),2).str_pad($temp_code,6,"0",STR_PAD_LEFT);
                    $model->vcode="0000";                    
                    $model->save();
                }
                $transaction->commit(); //提交事务
                Yii::app()->user->setFlash('success','操作成功！');
                $this->redirect(array('Party/admin'));                                 
            }  else {
                 Yii::app()->user->setFlash('upload_error','请选择上传文件！');
                $this->redirect(array('Party/create'));                   
            }
        }
        
        function generate_code($length = 4) {
            return rand(pow(10,($length-1)), pow(10,$length)-1);
        }
        /**
         * 
         * @param type $code
         * @return string通过身份证获取年龄
         */
        function getAgeByCode($code){ 

        //过了这年的生日才算多了1周岁 
                if(empty($code)) return ''; 
                $date=strtotime(substr($code,6,8));
        //获得出生年月日的时间戳 
                $today=strtotime('today');
        //获得今日的时间戳 
                $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数 

        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比 
                $age=strtotime(substr($code,6,8).' +'.$diff.'years')>$today?($diff+1):$diff; 

                return $age; 
            }         
        
}
